#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 生产环境配置
PROD_CONTAINER_NAME="fastapi_mysql"
PROD_DB_NAME="fastapi_auth"
PROD_DB_USER="root"
PROD_DB_PASSWORD="lh540308"

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}错误：请提供SQL文件路径${NC}"
    echo -e "${YELLOW}用法: $0 <sql_file_path>${NC}"
    exit 1
fi

SQL_FILE="$1"

# 检查SQL文件是否存在
if [ ! -f "$SQL_FILE" ]; then
    echo -e "${RED}错误：SQL文件不存在: $SQL_FILE${NC}"
    exit 1
fi

echo -e "${BLUE}=== 从SQL文件导入数据 ===${NC}"
echo -e "${YELLOW}SQL文件: $SQL_FILE${NC}"
echo -e "${YELLOW}目标容器: $PROD_CONTAINER_NAME${NC}"
echo -e "${YELLOW}目标数据库: $PROD_DB_NAME${NC}"

# 检查容器是否运行
if ! docker ps | grep -q "$PROD_CONTAINER_NAME"; then
    echo -e "${RED}错误：容器 $PROD_CONTAINER_NAME 未运行${NC}"
    exit 1
fi

# 备份当前生产数据库
BACKUP_FILE="./backup_$(date +%Y%m%d_%H%M%S).sql"
echo -e "${YELLOW}备份当前生产数据库...${NC}"
docker exec "$PROD_CONTAINER_NAME" mysqldump -u"$PROD_DB_USER" -p"$PROD_DB_PASSWORD" "$PROD_DB_NAME" > "$BACKUP_FILE"
echo -e "${GREEN}✓ 备份已保存到: $BACKUP_FILE${NC}"

# 复制SQL文件到容器
echo -e "${YELLOW}复制SQL文件到容器...${NC}"
docker cp "$SQL_FILE" "$PROD_CONTAINER_NAME:/tmp/import.sql"

# 导入SQL文件 - 修复这里的命令
echo -e "${YELLOW}导入SQL文件到数据库...${NC}"
docker exec "$PROD_CONTAINER_NAME" sh -c "mysql -u$PROD_DB_USER -p$PROD_DB_PASSWORD $PROD_DB_NAME < /tmp/import.sql"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ SQL文件导入成功${NC}"
    
    # 清理临时文件
    docker exec "$PROD_CONTAINER_NAME" rm -f /tmp/import.sql
    
    # 验证导入结果
    echo -e "${YELLOW}验证导入结果...${NC}"
    TABLE_COUNT=$(docker exec "$PROD_CONTAINER_NAME" mysql -u"$PROD_DB_USER" -p"$PROD_DB_PASSWORD" -e "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema='$PROD_DB_NAME';" --skip-column-names 2>/dev/null | tail -1)
    echo -e "${GREEN}✓ 数据库表数量: $TABLE_COUNT${NC}"
else
    echo -e "${RED}✗ SQL文件导入失败${NC}"
    echo -e "${YELLOW}可以使用备份文件恢复: $BACKUP_FILE${NC}"
    exit 1
fi

echo -e "${BLUE}=== 导入完成 ===${NC}"